// store/modules/item.js
import request from "@/utils/request";
const state = {
  firstDailyData: {},
  dailyData: [],
  firstBeautyData: {},
  beautyData: [],
  firstApplianceData: {},
  applianceData: [],
  firstDigitalData: {},
  digitalData: [],
  itemShopData: [],
  digitalDataAll: [],
  beautyDataAll: [],
  fashionistaData: [],
};

const mutations = {
  SET_ITEM_DATA(state, payload) {
    Object.assign(state, payload);
  },
};

const actions = {
  async fetchItemData({ commit }) {
    const res = await request.get("/item/getAll");
    const data = res.data;
    const dailyItems = data.filter((item) => item.type === 1);
    const beautyItems = data.filter((item) => item.type === 2);
    const applianceItems = data.filter((item) => item.type === 3);
    const digitalItems = data.filter((item) => item.type === 4);
    const fashionistaItems = data.filter((item) => item.type === 5);

    function shuffle(arr) {
      for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]];
      }
    }

    shuffle(dailyItems);
    shuffle(beautyItems);
    shuffle(applianceItems);
    shuffle(digitalItems);

    commit("SET_ITEM_DATA", {
      firstDailyData: dailyItems[0],
      dailyData: dailyItems.slice(1, 5),
      firstBeautyData: beautyItems[0],
      beautyData: beautyItems.slice(1, 5),
      firstApplianceData: applianceItems[0],
      applianceData: applianceItems.slice(1, 5),
      firstDigitalData: digitalItems[0],
      digitalData: digitalItems.slice(1, 5),
      itemShopData: data,
      digitalDataAll: digitalItems,
      beautyDataAll: beautyItems,
      fashionistaData: fashionistaItems,
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
